import os
import time
import tushare as ts
import pandas as pd


def GetAndSaveOneData(code_id,conn, start_date= '2000-01-01', end_data='2019-2-13'):
    df1 = ts.bar(code_id, conn=conn, freq='1min', start_date='2015-01-01', end_date=end_data)
    time.sleep(1)
    df5 = ts.bar(code_id, conn=conn, freq='5min', start_date='2015-01-01', end_date=end_data)
    #df15 = ts.bar(code_id, conn=con, freq='15min', start_date=start_date, end_date='')
    #df30 = ts.bar(code_id, conn=con, freq='30min', start_date=start_date, end_date='')
    #df60 = ts.bar(code_id, conn=con, freq='60min', start_date=start_date, end_date='')
    time.sleep(1)
    dfD = ts.bar(code_id, conn=conn, freq='D', start_date=start_date, end_date=end_data)
    if not(df1 is None or  df5 is None or   dfD is None) :
        df1.to_csv("H:\股票\\1\\"+code_id+".csv")
        df5.to_csv("H:\股票\\5\\"+code_id+".csv")
        dfD.to_csv("H:\股票\\D\\"+code_id+".csv")
        return True
    return False
pro = ts.pro_api(token="afe76ef7e99b9361a697bfa4559d677b2298d6047586c92b2dd3b3e4")
con=ts.get_apis()
#查询当前所有正常上市交易的股票列表
#GetAndSaveOneData("600260",con )
#data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')

#data1 = pro.daily(ts_code="600260.sh", start_date='20180701', end_date='20180718',freq="1" )
#data2 = ts.get_hist_data('600260', ktype="5") #一次性获取全部日k线数据
#data3 = ts.get_report_data(2014,3)
#data3 = ts.get_h_data('600260')
#df = ts.get_tick_data('600848', date='2014-01-09')
#df = ts.pro_bar('600000', conn=cons, freq='1min', start_date='2016-01-01', end_date='')
f = open('H:\股票\\hasDown.txt', 'r')
lsHasDown=[]
a = f.readline()
while a!="":
    lsHasDown.append(a[:-1])
    a = f.readline()
f.close()
allInfo = ts.get_stock_basics()
allInfo.to_csv("H:\股票\\allInfo.txt")
lsRowName =  allInfo._stat_axis.values.tolist()
fWrite = open('H:\股票\\hasDown.txt', 'a')

for dataCode in lsRowName:
    print(time.strftime("%Y-%m-%d %H:%M:%S  ",  time.gmtime(time.time()))+"准备采集:"+dataCode+":"+allInfo.loc[dataCode]["name"]+"\n")
    if dataCode not in lsHasDown:
        print(time.strftime("%Y-%m-%d %H:%M:%S  ", time.gmtime(time.time())) + "正在采集:" + dataCode + ":" + allInfo.loc[dataCode]["name"] + "\n")
        if GetAndSaveOneData(dataCode,con ):
            fWrite.write(dataCode)
            fWrite.write("\n")
            fWrite.flush()
            time.sleep(10)
    print(time.strftime("%Y-%m-%d %H:%M:%S  ",  time.gmtime(time.time()))+"结束采集:"+dataCode+":"+allInfo.loc[dataCode]["name"]+"\n")

